package com.newenergy.light.Helper;


import android.util.Log;

import com.newenergy.light.ble.HeaderHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by dell on 2016/12/6.
 */

public class BleDataHelper {

//    public static Context mContext;
//
//    public static void init(Context context) {
//        mContext = context;
//    }

//    private static String createAppId2() {
//        Random random = new Random(System.currentTimeMillis());
//        StringBuffer buffer = new StringBuffer();
//        for (int i = 0; i < 4; i++) {
//            int number = random.nextInt(255);
//            String hex = BleDataHelper.numberToHex(number);
//            buffer.append(hex);
//        }
//        String appId = buffer.toString();
//        return appId;
//    }
//
//    /**
//     * 根据蓝牙MAC地址生成APPid
//     *
//     * @return
//     */
//    private static String createAppId() {
//        String appId = "";
//        String bleAddress = "";
//        if (Build.VERSION.SDK_INT >= 23) {
//            bleAddress = android.provider.Settings.Secure
//                    .getString(mContext.getContentResolver(),
//                            "bluetooth_address");
//        } else {
//            bleAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
//
//        }
//        String[] macs = bleAddress.split(":");
//        if (macs.length == 6) {
//            appId = macs[1] + macs[3] + macs[4] + macs[5];
//            appId = appId.toUpperCase();
//        }
//        return appId;
//    }
//
//    public static String getAppId() {
//        String appId = SPUtil.getString("APP_ID", "");
//        if (TextUtils.isEmpty(appId)) {
//            appId = createAppId();
//            SPUtil.put("APP_ID", appId);
//        }
//        return "12345678";
//    }

    /**
     * 将Byte数组转换成16进制字符串
     * 指定最多接收多长数据
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes, int
            receiveDataLen) {
        String result = "";
        String sp = "-";
        int len = bytes.length > receiveDataLen ? receiveDataLen :
                bytes.length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            if (i < len - 1) {
                //将字符转换为大写
                result += hexString.toUpperCase() + sp;
            } else {
                result += hexString.toUpperCase();
            }
        }
        return result;
    }

    /**
     * 将Byte数组转换成16进制字符串
     * 指定最多接收多长数据
     *
     * @param bytes
     * @return
     */
    public static String bytesToStr(byte[] bytes, int
            receiveDataLen) {
        String result = "";
        int len = bytes.length > receiveDataLen ? receiveDataLen :
                bytes.length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }


    /**
     * 将Byte数组转换成16进制字符串
     * 指定最多接收多长数据
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        String result = "";
        String sp = "-";
        int len = bytes.length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            if (i < len - 1) {
                //将字符转换为大写
                result += hexString.toUpperCase();
            } else {
                result += hexString.toUpperCase();
            }
        }
        return result;
    }

    /**
     * 把a转成指定进制
     *
     * @param a
     * @param n
     * @return
     */
    public static String numberChange(int a, int n) {
        String str = "";
        //1:用a去除以n，得到商和余数
        int sun = a / n;
        int yuShu = a % n;
        str = "" + numberToLetter(yuShu);
        while (sun > 0) {
            //2：继续用商去除以n，得到商和余数
            yuShu = sun % n;
            sun = sun / n;
            //3：如果商为0，那么就终止
            //4：把所有的余数倒序排列
            str = numberToLetter(yuShu) + str;
        }

        if (a < 16) {
            String k = "0" + str;
            str = k;
        }
        return str;
    }

    public static String numberToHex(int a) {
//        a = a > 255 ? 255 : a;
        String str = "";
        // 1:用a去除以16，得到商和余数
        int sun = a / 16;
        int yuShu = a % 16;
        str = "" + numberToLetter(yuShu);
        while (sun > 0) {
            // 2：继续用商去除以16，得到商和余数
            yuShu = sun % 16;
            sun = sun / 16;
            // 3：如果商为0，那么就终止
            // 4：把所有的余数倒序排列
            str = numberToLetter(yuShu) + str;
        }
//        System.out.println("str  ==" + str);
        str = str.length() > 1 ? str : "0" + str;
        return str;
    }

    /**
     * 获取序号
     *
     * @param a
     * @return
     */
    public static String numberToSerial(int a) {
        String str = "";
        // 1:用a去除以16，得到商和余数
        int sun = a / 16;
        int yuShu = a % 16;
        str = "" + numberToLetter(yuShu);
        while (sun > 0) {
            // 2：继续用商去除以16，得到商和余数
            yuShu = sun % 16;
            sun = sun / 16;
            // 3：如果商为0，那么就终止
            // 4：把所有的余数倒序排列
            str = numberToLetter(yuShu) + str;
        }
//        System.out.println("str  ==" + str);
        str = modifyStr(str);
        return str;
    }

    /**
     * 给字符串补0
     *
     * @param str
     * @return
     */
    private static String modifyStr(String str) {
        int length = str.length();
        switch (length) {
            case 1:
                str = "000" + str;
                break;
            case 2:
                str = "00" + str;
                break;
            case 3:
                str = "0" + str;
                break;
        }
        return str;
    }

    /**
     * 将数字转化为字母
     *
     * @param a
     * @return
     */
    public static String numberToLetter(int a) {
        switch (a) {
            case 10:
                return "A";
            case 11:
                return "B";
            case 12:
                return "C";
            case 13:
                return "D";
            case 14:
                return "E";
            case 15:
                return "F";
        }
        return "" + a;
    }

    /**
     * 判断一个字符串是否含有数字
     */
    public static boolean HasDigit(String content) {
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }

    /**
     * 截取指定位置指定长度的字符串
     */
    public static String subString(String content, int start, int
            length) {
        return content.substring(start, start + length);
    }


    /**
     * 截取指定位置和长度的字节字符串
     * subHexStr(content,5,4) 获取新系统码
     * subHexStr(content,9,2) 获取序号
     * subHexStr(content,12,13)  获取需要解密数据
     */
    public static String subHexStr(String content, int index, int
            len) {
        index *= 2;
        len *= 2;
        return content.substring(index, index + len);
    }

    /**
     * 将字节数组转成普通字符串
     */
    public static String bytesToString(byte[] bytes, int length) {
        String result = "";
        int len = (bytes.length <= length) ? bytes.length : length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }

    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param s 16进制表示的字符串
     * @return byte[] 字节数组
     */

    public static byte[] StrToBytes(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) <<
                    4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return b;
    }


    public static String buildData(int... pwms) {

        StringBuffer buffer = new StringBuffer("");
        for (int i = 0; i < pwms.length; i++) {
            int pwm = pwms[i];
            pwm = modifyPwm(pwm);
            String hex = Integer.toHexString(pwm);
            if (hex.length() % 2 != 0) {
                hex = "0" + hex;
            }
            buffer.append(hex.toUpperCase());
//            buffer.append(BleDataHelper.numberToHex(pwm));
        }
        return buffer.toString();
    }

    public static int modifyPwm(int pwm) {
        pwm = pwm < 0 ? 0 : pwm;
        pwm = pwm > 250 ? 250 : pwm;
        return pwm;
    }


    /**
     *
     * @param cmdData 发送加密的数据
     * @param advertiseType 发送数据的类别
     * @param deviceType
     * @param zf
     * @return
     */
    public static byte[] getSendData(String cmdData,int advertiseType,String deviceType, String  zf) {
        String cmd = "";
        if (deviceType.equals("7201")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getBallLightSerial() + zf + cmdData;
        } else if (deviceType.equals("7202")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getFanSerial() + zf + cmdData;
        } else if (deviceType.equals("7203")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getFanLampSerial() + zf + cmdData;
        } else if (deviceType.equals("7204")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getElectricHeaterSerial() + zf + cmdData;
        } else if (deviceType.equals("7205")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getBathHeaterSerial() + zf + cmdData;
        } else if (deviceType.equals("7206")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getCurtainSerial() + zf + cmdData;
        } else if (deviceType.equals("7207")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getClotheshorseSerial() + zf + cmdData;
        } else if (deviceType.equals("7208")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getAirConditioningSerial() + zf + cmdData;
        }else if (deviceType.equals("7209")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getHealthBasinSerial() + zf + cmdData;
        }else if (deviceType.equals("720B")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getSplitSwitchSerial() + zf + cmdData;
        }else if (deviceType.equals("720D")) {
            if (advertiseType == 2) {
                deviceType = "5F48";
            }
            cmd = deviceType + getHumidifierSerial() + zf + cmdData;
        }
//        Log.i("QBH","发送数据 lenght="+cmd.length()+"   cmd="+cmd);
        return StrToBytes(cmd);
    }

    /**
     * 获取球泡灯下一个发送序号
     */
    public static String getBallLightSerial() {
        String key = "BALLLIGHT_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取风扇下一个发送序号
     */
    public static String getFanSerial() {
        String key = "FAN_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取风扇灯下一个发送序号
     */
    public static String getFanLampSerial() {
        String key = "FANLAMP_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取电暖器下一个发送序号
     */
    public static String getElectricHeaterSerial() {
        String key = "ELECTRICHEATER_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial =numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取浴霸下一个发送序号
     */
    public static String getBathHeaterSerial() {
        String key = "BATHHEATER_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取窗帘下一个发送序号
     */
    public static String getCurtainSerial() {
        String key = "CURTAIN_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }


    /**
     * 获取晾衣架下一个发送序号
     */
    public static String getClotheshorseSerial() {
        String key = "CLOTHESHORSE_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取空调下一个发送序号
     */
    public static String getAirConditioningSerial() {
        String key = "AIRCONDITIONING_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取养生盆下一个发送序号
     */
    public static String getHealthBasinSerial() {
        String key = "HEALTHBASIN_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }


    /**
     * 获取分电开关下一个发送序号
     */
    public static String getSplitSwitchSerial() {
        String key = "SPLITSWITCH_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }

    /**
     * 获取加湿器下一个发送序号
     */
    public static String getHumidifierSerial() {
        String key = "HUMIDIFIER_SERIAL";
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        serial_number++;
        if (serial_number > 4095) {
            serial_number = 1;
        }
        SPUtil.put(key, serial_number);
        return serial;
    }


    /**
     * 获取当前的类别发送序号
     */
    public static String getCurrentSerial(String deviceType) {
        String key = "";
        if (deviceType.equals("7201")) {//球泡灯
             key = "BALLLIGHT_SERIAL";
        } else if (deviceType.equals("7202")) {//风扇
            key = "FAN_SERIAL";
        }else if (deviceType.equals("7203")) {//风扇灯
            key = "FANLAMP_SERIAL";
        }else if (deviceType.equals("7204")) {//电暖器
            key = "ELECTRICHEATER_SERIAL";
        }else if (deviceType.equals("7205")) {//浴霸
            key = "BATHHEATER_SERIAL";
        }else if (deviceType.equals("7206")) {//窗帘
            key = "CURTAIN_SERIAL";
        }else if (deviceType.equals("7207")) {//晾衣架
            key = "CLOTHESHORSE_SERIAL";
        }else if (deviceType.equals("7208")) {//空调
            key = "AIRCONDITIONING_SERIAL";
        }else if (deviceType.equals("7209")) {//养生盆
            key = "HEALTHBASIN_SERIAL";
        }else if (deviceType.equals("720B")) {//分电开关
            key = "SPLITSWITCH_SERIAL";
        }else if (deviceType.equals("720D")) {//加湿器
            key = "HUMIDIFIER_SERIAL";
        }
        int serial_number = SPUtil.getInteger(key, 1);
        String serial = numberToSerial(serial_number);
        return serial;
    }


    /*byte[] bytes={(byte)0x02,(byte)0x01,(byte)0x1A,(byte)0x15,(byte)0x03,(byte)0x4E,(byte)0x6F,(byte)0x72,(byte)0x64,(byte)0x00,(byte)0x59,(byte)0x06,
            (byte)0x03,(byte)0xC9,(byte)0xD5,(byte)0xEA,(byte)0x0A,(byte)0xFA,(byte)0x00,(byte)0xFB,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0xFA,
            (byte)0x09};*/


    public static String[] checkScanData(byte[] bytes) {
        if (bytes.length < 25) return null;
        String scanData = bytesToString(bytes, 25);
        String sytemId = subString(scanData, 10, 6);//系统id

        String cmdType =  subString(scanData, 24, 2);//命令类型
        String familyID = subString(scanData, 26, 8);//家庭码
        String deviceId =  subString(scanData, 34, 8);//设备ID-UUID
        String st = subString(scanData, 48, 2);

        if (!sytemId.equals("4E6F72") || !cmdType.equals("F1"))
            return null;

        Log.i("scanResult", "sytemId==" + sytemId + "    familyID==" +
                familyID + "/n  cmdType==" + cmdType + "   deviceId==" +
                deviceId + " st==" + st);
        String[] datas = {familyID, deviceId, st};
        return datas;
    }



  /*  public void checkScanData(byte[] bytes) {
        if (bytes.length < 25) return ;
        String scanData =  BleDataHelper.bytesToString(bytes, 25);
        String sytemId = BleDataHelper.subString(scanData, 10, 8);//系统id
        String cmdType =  BleDataHelper.subString(scanData, 24, 2);//命令类型
        String familyID = BleDataHelper.subString(scanData, 26, 8);//家庭码
        String deviceId =  BleDataHelper.subString(scanData, 34, 8);//设备ID-UUID
        String st =  BleDataHelper.subString(scanData, 48, 2);


        Log.i("scanResult", "sytemId==" + sytemId + "    familyID==" +
                familyID + "/n  cmdType==" + cmdType + "   deviceId==" +
                deviceId + " st==" + st);
    }
*/






    /**
     * 获取特征码
     *
     * @return
     */
    public static int getFeatrueId() {
        return HeaderHelper.convertHeaders((byte)
                0x4E, (byte) 0x6F);
    }

}
